package com.valenx.distributedmulticamerasystem;

import com.valenx.distributedmulticamerasystem.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import java.util.Arrays;

public class MainAbility extends Ability {
//===================================================onStart===================================================
//=============================================================================================================
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        //申请权限
        requestPermissions();
    }
//=============================================================================================================

    //*方法：申请权限*
    private void requestPermissions() {
        //声明权限数组
        String[] permissions = {
                SystemPermission.WRITE_MEDIA,
                SystemPermission.READ_MEDIA,
                SystemPermission.CAMERA,
                SystemPermission.MICROPHONE,
                SystemPermission.DISTRIBUTED_DATASYNC
        };
        //过滤掉已经拥有的权限并转成数组
        //向用户申请剩余的权限
        requestPermissionsFromUser(Arrays.stream(permissions)
                .filter(permission -> verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED).toArray(String[]::new), 0);
    }
//-------------------------------------------------------------------------------------------------------------

    //检查用户返回的权限申请结果
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        //如果权限或返回结果为空，直接return
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            return;
        }
        //返回结果非空，则逐一判断返回结果，如果权限没有被允许就终止Ability
        for (int grantResult : grantResults) {
            if (grantResult != IBundleManager.PERMISSION_GRANTED) {
                terminateAbility();
                break;
            }
        }
    }
//=============================================================================================================

}
